package com.android.wnba.util.db;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import static com.android.wnba.provider.WnbaDBProvider.SETTING_COL_KEY;
import static com.android.wnba.provider.WnbaDBProvider.SETTING_COL_VALUE;
import static com.android.wnba.provider.WnbaDBProvider.TABLE_SETTING;;

public class DBUtil {
	
	private static Uri getUri(Context context){
		return Uri.parse("content://"
				+ context.getPackageName()+ ".upgrade" + "/" + TABLE_SETTING);
	}

	/**
	 * 获取map表中某项值
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	public static String getMapValue(Context context, String key) {
		final ContentResolver cr = context.getContentResolver();
		String selection = SETTING_COL_KEY + "=?";
		String[] selectionArgs = new String[] { key };
		Uri uri = getUri(context);
		Cursor c = cr.query(uri, null, selection,
				selectionArgs, null);
		String value = null;
		if (c != null) {
			if (c.getCount() > 0 && c.moveToFirst()) {
				do {
					value = c.getString(c.getColumnIndex(SETTING_COL_VALUE));
				} while (c.moveToNext());
			}
			c.close();
		}
		return value;
	}

	/**
	 * 更新map表中某项值
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void setMapValue(Context context, String key, String value) {
		final ContentResolver cr = context.getContentResolver();
		String selection = SETTING_COL_KEY + "=?";
		String[] selectionArgs = new String[] { key };
		Uri uri = getUri(context);
		cr.delete(uri, selection, selectionArgs);

		ContentValues values = new ContentValues();
		values.put(SETTING_COL_KEY, key);
		values.put(SETTING_COL_VALUE, value);
		cr.insert(uri, values);
	}

	/**
	 * 删除map表中某项值
	 * 
	 * @param context
	 * @param key
	 */
	public static void removeMapValue(Context context, String key) {
		final ContentResolver cr = context.getContentResolver();
		String selection = SETTING_COL_KEY + "=?";
		String[] selectionArgs = new String[] { key };
		Uri uri = getUri(context);
		cr.delete(uri, selection, selectionArgs);
	}
}
